{extend name="app/shop/view/base.html"/}
{block name="resources"}
<style>
	.layui-form-item .layui-input-inline.end-time{
		float: none;
	}
	.goods_list .layui-table-body{max-height: 480px !important;}
	.forbidden{cursor:not-allowed;background-color: #eee;}
	.goods-title{display: flex;align-items: center;}
	.goods-title .goods-img{display: flex;align-items: center;justify-content: center;width: 55px;height: 55px;margin-right: 5px;}
	.goods-title .goods-img img{max-height: 100%;max-width: 100%;}
	.goods-title .goods-name{flex: 1;line-height: 1.6;}
	.form-wrap {position: relative;}
	.coupon-list {width: 1080px !important;}
	.examples {cursor: pointer; margin-left: 5px; line-height: 36px;}
	.layui-carousel>[carousel-item]>* {background: #fff !important;}
	.layui-carousel {position: absolute; top: 10px; left: 1330px; width: 300px !important; height: 610px !important; background: #fff;}
	.select-coupon-layer .layui-layer-content{
		overflow-y: scroll!important;
	}
</style>
{/block}
{block name="main"}
<div class="layui-form form-wrap">
	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>活动名称：</label>
		<div class="layui-input-block">
			<input type="text" name="pintuan_name" value="{$pintuan_info.data.pintuan_name}" lay-verify="required" autocomplete="off" class="layui-input len-long" maxlength="40">
		</div>
		<div class="word-aux">
			<p>活动名称将显示在活动列表中，方便商家管理</p>
		</div>
	</div>
	
	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>活动时间：</label>
		<div class="layui-inline">
			<div class="layui-input-inline len-mid">
				<input type="text" id="start_time" name="start_time" value="{:date('Y-m-d H:i:s', $pintuan_info.data.start_time)}" lay-verify="required" class="layui-input" autocomplete="off" readonly>
				<i class=" iconrili iconfont calendar"></i>
			</div>
			<span class="layui-form-mid">-</span>
			<div class="layui-input-inline len-mid end-time">
				<input type="text" id="end_time" name="end_time" value="{:date('Y-m-d H:i:s', $pintuan_info.data.end_time)}" lay-verify="required|time" class="layui-input" autocomplete="off" readonly>
				<input type="hidden" value="{$pintuan_info.data.end_time}" id="old_end_time">
				<i class=" iconrili iconfont calendar"></i>
			</div>
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>成团人数：</label>
		<div class="layui-input-block">
			<input type="number" name="pintuan_num" value="{$pintuan_info.data.pintuan_num}" lay-verify="required|sum" autocomplete="off" class="layui-input len-short" id="pintuan_num">
		</div>
		<div class="word-aux">
			<p>成团人数是指拼团成功需要参与拼团的人数，最少两人成团</p>
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>实际发货人数：</label>
		<div class="layui-input-block">
			<input type="number" name="chengtuan_num" value="{$pintuan_info.data.chengtuan_num}" lay-verify="required|actualnum" autocomplete="off" class="layui-input len-short">
		</div>
		<div class="word-aux">
			<p>实际发货人数是指拼团成功实际可以发货的人数，未发货的部分将退款，同时给于一定返利</p>
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>未发货返利设置：</label>
		<div class="layui-input-block">
			<input type="radio" name="reward_type" value="1" lay-filter="filter"  title="消费余额" {$pintuan_info.data.reward_type == 1 ? 'checked' : ''}>
			<input type="radio" name="reward_type" value="2" lay-filter="filter"  title="现金红包" {$pintuan_info.data.reward_type == 2 ? 'checked' : ''}>
			<input type="radio" name="reward_type" value="3" lay-filter="filter"  title="优惠券" {$pintuan_info.data.reward_type == 3 ? 'checked' : ''}>
			<input type="radio" name="reward_type" value="4" lay-filter="filter"  title="积分" {$pintuan_info.data.reward_type == 4 ? 'checked' : ''}>
		</div>
		<div class="word-aux">
			<p>未发货返利是指拼团成功但是实际未发货，系统会自动退款，同时获得对应的返利</p>
		</div>
	</div>

	<div class="layui-form-item fixed-term {$pintuan_info.data.reward_type == 3 ? 'layui-hide' : 'layui-show'}">
		<label class="layui-form-label">
			{if $pintuan_info.data.reward_type == 1}
				消费余额
			{elseif $pintuan_info.data.reward_type == 2/}
				现金红包
			{elseif $pintuan_info.data.reward_type == 4/}
				积分
			{/if}：
		</label>
		<div class="layui-input-block">
			<div class="layui-input-inline">
				<input type="number" value="{$pintuan_info.data.reward_type_num}" name="reward_type_num" lay-verify="reward_type_num" autocomplete="off" class="layui-input len-short">
			</div>
		</div>
	</div>

	<div class="layui-form-item coupon-list {$pintuan_info.data.reward_type == 3 ? 'layui-show' : 'layui-hide'}">
		<label class="layui-form-label">送优惠券：</label>
		<div class="layui-input-block">
			<div class="coupon-item coupon">
				<div class="discount-cont">
					<div><a href="javascript:;" class="text-color select-coupon">选择优惠券</a></div>
					<div class="word-aux" style="margin-left: 0">
						<p>请确认优惠券数量是否充足，优惠券数量不足将导致赠送失败</p>
					</div>
					<div>
						<table class="layui-table" lay-skin="nob" >
							<colgroup>
								<col width="30%">
								<col width="50%">
								<col width="20%">
							</colgroup>
							<thead>
								<tr>
									<th>优惠券</th>
									<th>优惠内容</th>
									<th style="text-align:center;">操作</th>
								</tr>
							</thead>
							<tbody>
								{if !empty($pintuan_info.data.coupon_list)}

								{foreach $pintuan_info.data.coupon_list as $k => $vo}
								<tr data-coupon="{$vo.coupon_type_id}">
									<td>{$vo.coupon_name }</td>
									{if $vo.at_least > 0 }
									<td>满{$vo.at_least }{$vo.type == 'discount' ? '打'. $vo.discount .'折' : '减' . $vo.money }</td>
									{else/}
									<td>无门槛，{$vo.type == 'discount' ? '打'. $vo.discount .'折' : '减' . $vo.money }</td>
									{/if}
									<td style="text-align:center;"><a href="javascript:;" onclick="deleteCoupon(this)" class="text-color">删除</a></td>
								</tr>
								{/foreach}

								{/if}
							</tbody>
						</table>
					</div>
				</div>
			</div>
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>拼团有效期：</label>
		<div class="layui-input-block">
			<div class="layui-input-inline len-short">
				<select class="pintuan-day"></select>
			</div>
			<div class="layui-form-mid">日</div>
			<div class="layui-input-inline len-short">
				<select class="pintuan-hour"></select>
			</div>
			<div class="layui-form-mid">时</div>
			<div class="layui-input-inline len-short">
				<select class="pintuan-minute"></select>
			</div>
			<div class="layui-form-mid">分</div>
		</div>
		<div class="word-aux">
			<p>提交订单后，在该时间范围内拼团成功才可购买</p>
		</div>
	</div>
	
	<div class="layui-form-item">
		<label class="layui-form-label">限制购买：</label>
		<div class="layui-input-block">
			<input type="number" name="buy_num" value="{$pintuan_info.data.buy_num}" lay-verify="num" autocomplete="off" class="layui-input len-short">
		</div>
		<div class="word-aux">
			<p>本次活动中一次最多可购买的商品数量</p>
		</div>
	</div>
	
	<div class="layui-form-item">
		<label class="layui-form-label">团长优惠：</label>
		<div class="layui-input-block">
			<input type="checkbox" name="is_promotion" {$pintuan_info.data.is_promotion == 1 ? 'checked' : ''} value="{$pintuan_info.data.is_promotion}" title="团长享受优惠价" lay-skin="primary" lay-filter="is_promotion">
		</div>
		<div class="word-aux">
			<p>开启团长(开团人)优惠后，团长将享受更优惠价格，有助于提高开团率和成团率</p>
		</div>
	</div>

	<div class="layui-form-item goods_list">
		<label class="layui-form-label">活动商品：</label>
		<div class="layui-input-block">
			<table id="selected_goods_list" lay-filter="selected_goods_list"></table>
		</div>
	</div>
	
	<div class="layui-form-item">
		<label class="layui-form-label">是否单独购买：</label>
		<div class="layui-input-inline">
			<input type="radio" name="is_single_buy" value="1" title="是" {$pintuan_info.data.is_single_buy == 1 ? 'checked' : ''}>
			<input type="radio" name="is_single_buy" value="0" title="否" {$pintuan_info.data.is_single_buy == 0 ? 'checked' : ''}>
		</div>
		<a onclick="showDemo()" class="examples text-color">查看示例</a>
	</div>
	
	<div class="layui-form-item">
		<label class="layui-form-label">是否虚拟成团：</label>
		<div class="layui-input-inline">
			<input type="radio" name="is_virtual_buy" value="1" title="是" {$pintuan_info.data.is_virtual_buy == 1 ? 'checked' : ''}>
			<input type="radio" name="is_virtual_buy" value="0" title="否" {$pintuan_info.data.is_virtual_buy == 0 ? 'checked' : ''}>
		</div>
	</div>
	
	<div class="layui-form-item layui-hide">
		<label class="layui-form-label">是否推荐：</label>
		<div class="layui-input-inline">
			<input type="radio" name="is_recommend" value="1" title="是" {$pintuan_info.data.is_recommend == 1 ? 'checked' : ''}>
			<input type="radio" name="is_recommend" value="0" title="否" {$pintuan_info.data.is_recommend == 0 ? 'checked' : ''}>
		</div>
	</div>
	
	<div class="layui-form-item layui-form-text">
		<label class="layui-form-label">活动规则：</label>
		<div class="layui-input-inline">
			<textarea name="remark" class="layui-textarea len-long" maxlength="300">{$pintuan_info.data.remark}</textarea>
		</div>
	</div>
	
	<div class="form-row">
		<button class="layui-btn" lay-submit lay-filter="save">保存</button>
		<button class="layui-btn layui-btn-primary" onclick="back()">返回</button>
	</div>
	
	<input type="hidden" name="pintuan_id" value="{$pintuan_info.data.pintuan_id}" />
	<input type="hidden" class="pintuan-time" value="{$pintuan_info.data.pintuan_time}" />
	<input type="hidden" name="goods_id" class="goods-id" value="{$pintuan_info.data.goods_id}" />
	<input type="hidden" name="is_virtual_goods" class="is-virtual-goods" value="{$pintuan_info.data.is_virtual_goods}" />
	<input type="hidden" class="start-time-pri" value="{$pintuan_info.data.start_time}" />
	<input type="hidden" class="end-time-pri" value="{$pintuan_info.data.end_time}" />
	
<!--	<div class="layui-carousel" id="carousel">
	  <div carousel-item>
	   <img  src="__STATIC__/img/pinfan.png" >
	  </div>
	</div>-->
	
</div>
{/block}
{block name="script"}

<!-- 优惠券 -->
<script type="text/html" id="couponList">
	<div class="gift-box">
		<div class="single-filter-box">
			<div class="layui-form">
				<div class="layui-input-inline">
					<input type="text" name="coupon_name" placeholder="请输入优惠券名称" class="layui-input len-mid">
					<button type="button" class="layui-btn layui-btn-primary" lay-filter="coupon-search" lay-submit>
						<i class="layui-icon">&#xe615;</i>
					</button>
				</div>
			</div>
		</div>
		<table id="coupon_list" lay-filter="coupon_list"></table>
	</div>
</script>

<!-- 优惠券-名称 -->
<script type="text/html" id="couponName">
	<div class="table-tuwen-box">
		<div class="font-box">
			<p class="multi-line-hiding">{{d.coupon_name}}</p>
		</div>
	</div>
</script>

<!-- 优惠券-操作 -->
<script type="text/html" id="couponOperation">
	{{# var select_coupon_list = ','+coupon_list+','}}
	{{# if(select_coupon_list.indexOf(','+d.coupon_type_id+',') != -1){ }}
	<p title="该优惠券已参加">已添加</p>
	{{# }else{ }}
	<a class="layui-btn" lay-event="add">添加</a>
	{{# } }}
</script>

<script type="text/html" id="toolbarOperation">
	<button class="layui-btn layui-btn-primary" lay-event="pintuan-price">拼团价格</button>
</script>

<script type="text/html" id="toolbarOperationOne">
	<button class="layui-btn layui-btn-primary" lay-event="pintuan-price">拼团价格</button>
	<button class="layui-btn layui-btn-primary" lay-event="pintuan-discounts-price">团长优惠价</button>
</script>

<script>
	var start_time_pri = ns.time_to_date($(".start-time-pri").val()),
		end_time_pri = ns.time_to_date($(".end-time-pri").val());
	var pintuan_time = $(".pintuan-time").val(), //总分钟数
		
		day_time = pintuan_time / (24 * 60), //天数
		houe_time = (pintuan_time % (24 * 60)) / 60, //小时
		second_time = (pintuan_time % (24 * 60)) % 60; //分钟
	var coupon_list = '{$pintuan_info.data.reward_type_num}';
	var sku_list = [];
	sku_list = {:json_encode($pintuan_info.data.sku_list, JSON_UNESCAPED_UNICODE)};

	var pintuan_info = {:json_encode($pintuan_info.data,JSON_UNESCAPED_UNICODE)},is_promotion = 0;
	sku_list.forEach(function (item,index) {
		item.is_delete = item.pintuan_price ? 1 : 2;
	});

	var is_virtual = [];
	var laytpl;
	layui.use(['form', 'laydate','carousel','laytpl'], function() {
		var form = layui.form,
			laydate = layui.laydate,
			repeat_flag = false,
			minDate = "";
			var carousel = layui.carousel;
		laytpl = layui.laytpl;
			carousel.render({
			   elem: '#carousel'
			   ,width: '100%' 
			   ,arrow: 'always' 
			 });
			 
		form.render();
		if(pintuan_info.is_promotion == 1){
			renderTableGroup(sku_list);
			is_promotion = 1;
		}else{
			renderTable(sku_list); // 初始化表格
			is_promotion = 0;
		}

		for (var i = 0; i <= 30; i++) {
			if (i < 10) {
				if (i == day_time) {
					var html = '<option value="' + i + '" selected>0' + i + '</option>';
				} else {
					var html = '<option value="' + i + '">0' + i + '</option>';
				}
			} else {
				if (i == day_time) {
					var html = '<option value="' + i + '" selected>' + i + '</option>';
				} else {
					var html = '<option value="' + i + '">' + i + '</option>';
				}
			}
			$(".pintuan-day").append(html);
		}
		for (var i = 0; i <= 23; i++) {
			if (i < 10) {
				if (i == houe_time) {
					var html = '<option value="' + i + '" selected>0' + i + '</option>';
				} else {
					var html = '<option value="' + i + '">0' + i + '</option>';
				}
			} else {
				if (i == houe_time) {
					var html = '<option value="' + i + '" selected>' + i + '</option>';
				} else {
					var html = '<option value="' + i + '">' + i + '</option>';
				}
			}
			$(".pintuan-hour").append(html);
		}
		for (var i = 0; i <= 59; i++) {
			if (i < 10) {
				if (i == second_time) {
					var html = '<option value="' + i + '" selected>0' + i + '</option>';
				} else {
					var html = '<option value="' + i + '">0' + i + '</option>';
				}
			} else {
				if (i == second_time) {
					var html = '<option value="' + i + '" selected>' + i + '</option>';
				} else {
					var html = '<option value="' + i + '">' + i + '</option>';
				}
			}
			$(".pintuan-minute").append(html);
		}
		form.render('select');

		var now_time = ((new Date()).getTime())/1000;
		var start_time = ((new Date($("#start_time").val())).getTime())/1000;
		var old_end_time = ((new Date($("#end_time").val())).getTime())/1000;
		if(now_time <= start_time){
			//开始时间
			laydate.render({
				elem: '#start_time', //指定元素
				type: 'datetime',
				value: start_time_pri,
				done: function(value) {
					minDate = value;
					reRender();
				}
			});
		}
		if(now_time <= old_end_time){
			//结束时间
			laydate.render({
				elem: '#end_time', //指定元素
				type: 'datetime',
				value: end_time_pri
			});
		}

		// 监听单选按钮
		form.on('radio(filter)', function (data) {
			if(data.value == 1){
				$('.fixed-term .layui-form-label').html('消费余额：')
			}else if(data.value == 2){
				$('.fixed-term .layui-form-label').html('现金红包：')
			}else if(data.value == 4){
				$('.fixed-term .layui-form-label').html('积分：')
			}

			if (data.value == 3) {
				$('.coupon-list').removeClass('layui-hide');
				$('.fixed-term').addClass('layui-hide');

			} else {
				$('.fixed-term').removeClass('layui-hide');
				$('.coupon-list').addClass('layui-hide');

			}
		});
		/**
		 * 重新渲染结束时间
		 * */
		function reRender() {
			$("#end_time").remove();
			$(".end-time").html('<input type="text" id="end_time" name="end_time" placeholder="请输入结束时间" lay-verify="required|time" class ="layui-input" autocomplete="off" readonly><i class=" iconrili iconfont calendar"></i> ');
			laydate.render({
				elem: '#end_time',
				type: 'datetime',
				min: minDate
			});
		}
		
		/**
		 * 表单验证
		 */
		form.verify({
			time: function(value) {
				var now_time = ((new Date()).getTime())/1000;
				var start_time = ((new Date($("#start_time").val())).getTime())/1000;
				var end_time = ((new Date(value)).getTime())/1000;
				var old_end_time = $("#old_end_time").val();

		        if(old_end_time > end_time){
					return '结束时间不能小于之前设置的结束时间!'
				}
				if (now_time > end_time) {
					return '结束时间不能小于当前时间!'
				}
				if (start_time > end_time) {
					return '结束时间不能小于开始时间!';
				}
			},
			num: function(value) {
				if (value < 1 || value % 1 != 0) {
					return '请输入大于0的正整数！';
				}
			},
			reward_type_num:function(value){
				if(value<0){
					return '必须大于0';
				}
			},
			sum: function(value) {
				if (value < 2 || value % 1 != 0) {
					return '参团人数不能小于2，且必须是整数！';
				}
			},
			actualnum: function(value){
				var nownum = $("#pintuan_num").val();
				if (Number(value) >= Number(nownum)) {
					return '成团人数必须大于实际发货人数';
				}
			},
			pintuan_price: function(value, item) {
				var price = $(item).parents("tr").find(".goods-price").text();
				if (Number(value) > Number(price)) {
					return '拼团价格不能大于商品价格';
				}
				if (value.trim() == "") {
					return '拼团价格不能为空';
				}
				if (Number(value) <= 0) {
					return '拼团价格必须大于0';
				}
				
				var arrMen = value.split(".");
				var val = 0;
				if (arrMen.length == 2) {
					val = arrMen[1];
				}
				if (val.length > 2) {
					return '拼团价格最多保留两位小数';
				}
			},
			promotion_price: function(value, item) {
				var price = $(item).parents("tr").find(".goods-price").text();
				if (Number(value) > Number(price)) {
					return '团长优惠价不能大于商品价格';
				}
				if (value.trim() == "") {
					return '团长优惠价不能为空';
				}
				if (Number(value) <= 0) {
					return '团长优惠价必须大于0';
				}
				
				var arrMen = value.split(".");
				var val = 0;
				if (arrMen.length == 2) {
					val = arrMen[1];
				}
				if (val.length > 2) {
					return '团长优惠价最多保留两位小数';
				}
			}
		});
		
		/**
		 * 监听团长优惠是否被选中
		 */
		form.on('checkbox(is_promotion)', function(data){
			if (data.elem.checked) {
				$(".team-leader").removeClass("layui-hide");
				$(".goods-empty").attr("colspan", 4);
				$("input[name='is_promotion']").val(1);
				renderTableGroup(sku_list);
				is_promotion = 1;
			} else {
				$(".team-leader").addClass("layui-hide");
				$(".goods-empty").attr("colspan", 3);
				$("input[name='is_promotion']").val(0);
				renderTable(sku_list);
				is_promotion = 0;
			}
		});
		
		/**
		 * 监听提交
		 */
		form.on('submit(save)', function(data){
			if(data.field.reward_type == 1){
				if(data.field.reward_type_num==''){
					layer.msg("消费余额不为空！", {icon: 5, anim: 6});
					return;
				}
			}
			if(data.field.reward_type == 2){
				if(data.field.reward_type_num==''){
					layer.msg("现金红包不为空！", {icon: 5, anim: 6});
					return;
				}
			}
			if(data.field.reward_type == 4){
				if(data.field.reward_type_num==''){
					layer.msg("积分不为空！", {icon: 5, anim: 6});
					return;
				}
			}
			if(data.field.reward_type == 3){
				data.field.reward_type_num = coupon_list;
				if(coupon_list.split(',').length==0||coupon_list==''){
					layer.msg("请选择优惠券！", {icon: 5, anim: 6});
					return;
				}
			}
			data.field.sku_ids = [];
			data.field.goods_id = sku_list[0].goods_id;
			sku_list.forEach(function (item,index) {
				if (item.is_delete == 2) return false;
				data.field.sku_ids.push(item.sku_id);
			});
			if (data.field.sku_ids.length == 0) {
				layer.msg("请选择参与活动商品！", {icon: 5, anim: 6});
				return;
			}

			var skuLisArr = [];
			sku_list.forEach(function(item,index) {
				var sku_detail = {};
				sku_detail.sku_id = item.sku_id;
				sku_detail.goods_id = item.goods_id;
				sku_detail.pintuan_price = item.pintuan_price || 0;
				sku_detail.promotion_price = item.promotion_price || 0;
				sku_detail.is_delete = item.is_delete || 1;
				skuLisArr.push(sku_detail);
			});
			data.field.sku_list = skuLisArr;

			var day = $(".pintuan-day option:selected").text(),
				hour = $(".pintuan-hour option:selected").text(),
				minute = $(".pintuan-minute option:selected").text();
			
			var pintuan_time = Number(day) * 24 * 60 + Number(hour) * 60 + Number(minute);
			data.field.pintuan_time = pintuan_time;
			
			var time = new Date(data.field.end_time).getTime() - new Date(data.field.start_time).getTime();
			if (time < (pintuan_time * 60 * 1000)) {
				layer.msg("拼团有效期不能大于活动时长！", {icon: 5, anim: 6});
				return;
			}
			
			if (data.field.is_promotion == undefined) {
				data.field.is_promotion = 0;
			}

			if(repeat_flag) return;
			repeat_flag = true;
			
			$.ajax({
				type: 'POST',
				dataType: 'JSON',
				url: ns.url("pinfan://shop/pinfan/edit"),
				data: data.field,
				async: false,
				success: function(res){
					repeat_flag = false;
					
					if (res.code == 0) {
						layer.confirm('编辑成功', {
							title:'操作提示',
							btn: ['返回列表', '继续操作'],
							yes: function(){
								location.href = ns.url("pinfan://shop/pinfan/lists");
							}
						});
					}else{
						layer.msg(res.message);
					}
				}
			})
		});
	});

	// 表格渲染
	function renderTable(sku_list) {
		//展示已知数据
		table = new Table({
			elem: '#selected_goods_list',
			page:false,
			limit:Number.MAX_VALUE,
			cols: [
				[{
					width: "3%",
					type: 'checkbox',
					unresize: 'false'
				},{
					field: 'sku_name',
					title: '商品名称',
					width: '23%',
					unresize: 'false',
					templet: function(data) {
						var html = '';
						html += `
							<div class="goods-title">
								<div class="goods-img">
									<img layer-src src="${data.sku_image ? ns.img(data.sku_image) : ''}" alt="">
								</div>
								<p class="multi-line-hiding goods-name" data-goods_id="${data.goods_id}" data-sku_id="${data.sku_id}" title="${data.sku_name}">${data.sku_name}</p>
							</div>
						`;
						return html;
					}
				}, {
					field: 'price',
					title: '商品价格',
					unresize: 'false',
					width: '15%',
					templet: function(data) {
						return '<p class="line-hiding" title="'+ data.price +'">￥<span class="goods-price">' + data.price +'</span></p>';
					}
				}, {
					field: 'stock',
					title: '库存',
					unresize: 'false',
					width: '10%',
					templet: function(data) {
						return '<p class="stock">' + data.stock +'</p>';
					}
				}, {
					title: '拼团价格(元)',
					unresize: 'false',
					width: '13%',
					templet: '#pintuan_price'
				}, {
					title: '操作',
					toolbar: '#operation',
					unresize: 'false',
					align:'right'
				}]
			],
			data: sku_list,
			toolbar: '#toolbarOperation'
		});
		/**
		 * 批量操作
		 */
		table.toolbar(function(obj) {

			if (obj.data.length < 1) {
				layer.msg('请选择要操作的数据');
				return;
			}
			switch (obj.event) {
				case "pintuan-price":
					editInput(0,obj);
					break;
				case "pintuan-discounts-price":
					editInput(1,obj);
					break;
			}
		});
	}
	// 团长优惠价表格渲染
	function renderTableGroup(sku_list) {
		//展示已知数据
		table = new Table({
			elem: '#selected_goods_list',
			page:false,
			limit:Number.MAX_VALUE,
			cols: [
				[{
					width: "3%",
					type: 'checkbox',
					unresize: 'false'
				},{
					field: 'sku_name',
					title: '商品名称',
					width: '23%',
					unresize: 'false',
					templet: function(data) {
						var html = '';
						html += `
							<div class="goods-title">
								<div class="goods-img">
									<img layer-src src="${data.sku_image ? ns.img(data.sku_image) : ''}" alt="">
								</div>
								<p class="multi-line-hiding goods-name" data-goods_id="${data.goods_id}" data-sku_id="${data.sku_id}" title="${data.sku_name}">${data.sku_name}</p>
							</div>
						`;
						return html;
					}
				}, {
					field: 'price',
					title: '商品价格',
					unresize: 'false',
					width: '15%',
					templet: function(data) {
						return '<p class="line-hiding" title="'+ data.price +'">￥<span class="goods-price">' + data.price +'</span></p>';
					}
				}, {
					field: 'stock',
					title: '库存',
					unresize: 'false',
					width: '10%',
					templet: function(data) {
						return '<p class="stock">' + data.stock +'</p>';
					}
				}, {
					title: '拼团价格(元)',
					unresize: 'false',
					width: '13%',
					templet: '#pintuan_price'
				}, {
					title: '团长优惠价(元)',
					unresize: 'false',
					width: '13%',
					templet: '#promotion_price'
				}, {
					title: '操作',
					toolbar: '#operation',
					unresize: 'false',
					align:'right'
				}]
			],
			data: sku_list,
			toolbar: '#toolbarOperationOne'
		});
		/**
		 * 批量操作
		 */
		table.toolbar(function(obj) {

			if (obj.data.length < 1) {
				layer.msg('请选择要操作的数据');
				return;
			}
			switch (obj.event) {
				case "pintuan-price":
					editInput(0,obj);
					break;
				case "pintuan-discounts-price":
					editInput(1,obj);
					break;
			}
		});
	}
	function editInput(textIndex=0,data) {
		var text = [{
			name: '拼团价格',
			value: 'pintuan_price'
		},{
			name: '团长优惠价',
			value: 'promotion_price'
		}];

		layer.open({
			type: 1,
			title:"修改"+text[textIndex].name,
			area:['600px'],
			btn:["保存","返回"],
			content: `
			<div class="layui-form-item">
				<label class="layui-form-label"><span class="required">*</span>${text[textIndex].name}：</label>
				<div class="layui-input-block">
					<input type="text" name="bargain_edit_input" lay-verify="required" autocomplete="off" class="layui-input len-mid" placeholder="请输入${text[textIndex].name}">
				</div>
			</div>
		`,
			yes: function(index, layero){
				var val = $("input[name='bargain_edit_input']").val();
				if (!val){
					layer.msg("请输入" + text[textIndex].name);
					return false;
				}
				data.data.forEach(function (item,index) {
					sku_list.forEach(function (skuItem,skuIndex) {
						if (item.sku_id == skuItem.sku_id){
							sku_list[skuIndex][text[textIndex].value] = val;
						}
					})
				});
				if (is_promotion == 1){
					renderTableGroup(sku_list);
				}else{
					renderTable(sku_list);
				}
				layer.closeAll();
			}
		});
	}

	function bargainPintuanPrice(index,event) {
		sku_list[index-1].pintuan_price = event.srcElement.value;
	}
	function bargainPromotionPrice(index,event) {
		sku_list[index-1].promotion_price = event.srcElement.value;
	}

	$("body").on("click",".no-participation",function(){
		$(this).text("参与");
		$(this).parents("tr").find("input").each(function (index,item) {
			$(item).attr("readonly",true);
			$(item).attr("disabled",true);
			$(item).addClass("forbidden");
			$(item).attr("lay-verify","");
		});

		// pintuan_price  promotion_price  lay-verify
		$(this).addClass("participation").removeClass("no-participation");
		sku_list[$(this).parents("tr").attr("data-index")].is_delete = 2;
	});

	$("body").on("click",".participation",function(){
		$(this).text("不参与");
		$(this).parents("tr").find("input").each(function (index,item) {
			$(item).attr("readonly",false);
			$(item).attr("disabled",false);
			$(item).removeClass("forbidden");
			if($(item).hasClass(".pintuan-price")){
				$(item).attr("lay-verify","pintuan_price");
			}else{
				$(item).attr("lay-verify","promotion_price");
			}
		});

		$(this).removeClass("participation").addClass("no-participation");
		sku_list[$(this).parents("tr").attr("data-index")].is_delete = 1;
	});

	$('body').on('click', '.coupon-item .select-coupon', function(e){
		var event = this;
		layer.open({
			type: 1,
			area: ["1200px","600px"],
			title: '优惠券列表',
			skin: 'select-coupon-layer',
			content: $("#couponList").html()
		});

		couponTable = new Table({
			elem: "#coupon_list",
			url: ns.url("coupon://shop/coupon/lists"),
			where: {'status': 1,'inventory_count':1},
			cols: [
				[{
					title: '优惠券名称',
					unresize: 'false',
					width: '15%',
					templet: '#couponName'
				}, {
					title: '类型',
					unresize: 'false',
					width: '10%',
					templet: function(data){
						return data.type == 'discount' ? '折扣' : '满减'
					}
				}, {
					title: '优惠金额/折扣',
					unresize: 'false',
					width: '15%',
					templet: function(data){
						return data.type == 'discount' ? data.discount+'折' : data.money+'元';
					}
				}, {
					field: 'goods_type',
					title: '适用商品',
					unresize: 'false',
					width: '10%',
					templet: function (data) {
						if (data.goods_type == 1) {
							return '全部商品';
						} else if (data.goods_type == 2) {
							return '指定商品';
						} else if (data.goods_type == 3) {
							return '指定不参与商品';
						}
					}
				}, {
					field: 'max_fetch',
					title: '领取人限制',
					unresize: 'false',
					width: '10%'
				},{
					field: 'count',
					title: '已领取/发放数',
					unresize: 'false',
					width: '15%',
					templet: function(data){
						return data.count == -1 ? data.lead_count+'/不限量' : data.lead_count+'/'+data.count;
					}
				}, {
					field: 'gift_state',
					title: '结束时间',
					unresize: 'false',
					width: '15%',
					templet: function (res) {
						if(res.validity_type == 0){
							return ns.time_to_date(res.end_time);
						}else{
							return "领取之日起" + res.fixed_term + "天有效";
						}
					}
				}, {
					title: '操作',
					toolbar: '#couponOperation',
					unresize: 'false',
					align:'right'
				}]
			]
		});

		couponTable.tool(function(obj) {
			var data = obj.data;
			switch (obj.event) {
				case "add":
					addcoupon(data);
					break;
			}
		});

		function addcoupon(data){
			var template = `<tr data-coupon="{{ d.coupon_type_id }}">
				<td>{{ d.coupon_name }}</td>
				{{# if(d.at_least > 0){  }}
					<td>满{{ d.at_least }}{{ d.type == 'discount' ? '打'+ d.discount +'折' : '减' + d.money }}</td>
				{{# } else { }}
					<td>无门槛，{{ d.type == 'discount' ? '打'+ d.discount +'折' : '减' + d.money }}</td>
				{{# } }}
				<td style="text-align:center;"><a href="javascript:;" onclick="deleteCoupon(this)" class="text-color">删除</a></td>
			</tr>`;
			laytpl(template).render(data, function(string){
				$(event).parents('.discount-cont').find('.layui-table tbody').append(string);
				layer.closeAll();
			});
			getCoupon();
		}
	});

	// 删除优惠券
	function deleteCoupon(e){
		$(e).parents('tr').remove();
		getCoupon();
	}

	getCoupon();
	//获取已选中优惠券
	function getCoupon() {
		var reward_type_num = [];
		$('.coupon').find('tr[data-coupon]').each(function (i, e) {
			reward_type_num.push($(e).attr('data-coupon'));
		});
		coupon_list = reward_type_num.toString();
	}

	function back() {
		location.href = ns.url("pinfan://shop/pinfan/lists");
	}
	function showDemo(){
	    layer.open({
	        title: '查看示例',
	        type: 1,
	        area: ['600px', '660px'],
	        content: '<img style="margin:20px 45px;" src="__STATIC__/img/single_buy_two.png" >',
	    })
	}
</script>

<script type="text/html" id="pintuan_price">
	{{# if(!d.pintuan_price){ }}
	<input type="number" class="layui-input len-input pintuan-price forbidden" value="{{d.pintuan_price}}" min="0.00" oninput="bargainPintuanPrice({{ d.LAY_INDEX }},event)" onporpertychange="bargainPromotionPrice({{ d.LAY_INDEX }},event)" readonly disabled/>
	{{# }else{ }}
	<input type="number" class="layui-input len-input pintuan-price" value="{{d.pintuan_price}}" lay-verify="pintuan_price" min="0.00" oninput="bargainPintuanPrice({{ d.LAY_INDEX }},event)" onporpertychange="bargainPromotionPrice({{ d.LAY_INDEX }},event)"/>
	{{# } }}
</script>

<script type="text/html" id="promotion_price">
	{{# if(!d.pintuan_price){ }}
	<input type="number" class="layui-input len-input promotion-price forbidden" value="{{d.promotion_price}}" min="0.00" oninput="bargainPromotionPrice({{ d.LAY_INDEX }},event)" onporpertychange="bargainPromotionPrice({{ d.LAY_INDEX }},event)" readonly disabled/>
	{{# }else{ }}
	<input type="number" class="layui-input len-input promotion-price" value="{{d.promotion_price}}" lay-verify="promotion_price" min="0.00" oninput="bargainPromotionPrice({{ d.LAY_INDEX }},event)" onporpertychange="bargainPromotionPrice({{ d.LAY_INDEX }},event)"/>
	{{# } }}
</script>

<script type="text/html" id="operation">
	<div class="table-btn">
		{{# if(!d.pintuan_price){ }}
		<a class="layui-btn participation">参与</a>
		{{# }else{ }}
		<a class="layui-btn no-participation">不参与</a>
		{{# } }}
	</div>
</script>
{/block}